package me.chan.netty.framedecoder;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadLocalRandom;

@Slf4j
public class FixedLengthFrameClient {

    public static void main(String[] args) {

        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {

            ChannelFuture channelFuture = bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG))
                                            .addLast(new ChannelInboundHandlerAdapter(){
                                                @Override
                                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                                    ThreadLocalRandom random = ThreadLocalRandom.current();
                                                    char c = 'a';
                                                    ByteBuf buffer = ctx.alloc().buffer();
                                                    for (int i = 0; i < 10; i++) {
                                                        byte[] bytes = new byte[8];
                                                        for (int j = 0; j < random.nextInt(10); j++) {
                                                            bytes[j] = (byte) c;
                                                        }
                                                        c++;
                                                        buffer.writeBytes(bytes);
                                                    }
                                                    ctx.writeAndFlush(buffer);
                                                }
                                            });
                        }
                    }).connect("127.0.0.1", 8080).sync();
                    channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            log.error(ex.getLocalizedMessage());
        } finally {
            group.shutdownGracefully();
        }
    }
}
